<?php
class CCUModel extends BaseModel
{
    public static function calcCCU()
    {
        $sql = 'INSERT INTO ccu
                SELECT to_time, COUNT(DISTINCT a.user_id)
                FROM activity a,
                    (SELECT MAX(time) AS from_time, DATE_ADD(MAX(time),INTERVAL :interval MINUTE) AS to_time FROM ccu) c
                WHERE a.created_at BETWEEN c.from_time AND to_time';
        $command = Yii::app()->db->createCommand($sql);
        $command->bindParam(':interval', $interval = CONST_CCU_INTERVAL);
        $command->execute();
    }

    public static function getCCU()
    {
        $sql = 'SELECT * FROM ccu WHERE `time` >= DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY `time`';
        $command = Yii::app()->db->createCommand($sql);
        return $command->queryAll();
    }
}
